const db = wx.cloud.database()
const _ = db.command
var isCollect;
var isZan;
var textID;
var Zan;
let likeCollection = {}
const app = getApp()
Page({
  data: {
    navbar: ["项目", "图文", "组织", "排行"],
    index: "",
    currentTab: 0,
    current: "",
    textList: [],
    imgList: [
      "https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=508387608,2848974022&fm=26&gp=0.jpg",
    ],
    isZan:false,
    colUrl: "../../images/no_coll.png",
    comUrl: "../../images/com.png",
    projectList: [],
    order: 'desc',
    showChoose: false,
    conditionWhere: ['扶助困难群体', '发展农业生产', '促进邻里互助', '倡导文明风尚', '关怀儿童教育', '协调冲突矛盾', '保护生态环境', '其它'],
    tabbar: {},
    teamList: [],
    projectType0:[{id:0,type:'农业咨询'},{id:1,type:'法律咨询'},{id:2,type:'心理咨询'},
    {id:3,type:'文娱策划'},{id:4,type:'医疗咨询'},{id:5,type:'艺术咨询'},
    {id:6,type:'环境养护'}],
    project0Current:"",

    projectType1:[{id:0,type:'邻里互助'},{id:1,type:'儿童助学'},{id:2,type:'农业生产'},
    {id:3,type:'照顾老人'}],
    projec1Current:"",

    projectType2:[{id:0,type:'敬老爱老'},{id:1,type:'科学普及'},{id:2,type:'文明乡村'},
    {id:3,type:'信息普及'},{id:4,type:'政策普及'}],
    project2Current:"",

    projectType3:[{id:0,type:'核酸检测'},{id:1,type:'知识普及'},{id:2,type:'疫情教育'}],
    project3Current:"",


  },
  //上面导航栏的方法**************************************
  swiperChange(e) {
    let index = e.detail.current;
    console.log("切换顶部导航")
    this.setData({
      currentTab: index,
      current: index,
    })
  },
  navbarTap: function (e) {
    console.log(e)
    let index = e.currentTarget.dataset.idx;
    this.setData({
      currentTab: index
    })
  },
  //*************这是一条分割线**********************************************************/
  //关于项目的方法****************************************
  //筛选条件的弹出框
  showPopup() {
    this.setData({
      showChoose: true
    });
  },
  onClose() {
    this.setData({
      showChoose: false
    });
  },
  chooseCond(e)
  {
    console.log(e)
    let id=e.currentTarget.dataset.id
    this.setData({
      project0Current:id
    })
    this.getProjectList()
    if(id==0)
    {
      
    }
  },
  chooseCond1(e)
  {
    console.log(e)
    let id=e.currentTarget.dataset.id
    this.setData({
      project1Current:id
    })
    if(id==0)
    {
      
    }
    this.getProjectList()
  },
  chooseCond2(e)
  {
    console.log(e)
    let id=e.currentTarget.dataset.id
    this.setData({
      project2Current:id
    })
    if(id==0)
    {
      
    }
    this.getProjectList()
  },
  chooseCond3(e)
  {
    console.log(e)
    let id=e.currentTarget.dataset.id
    this.setData({
      project3Current:id
    })
    if(id==0)
    {
      
    }
    this.getProjectList()
  },
  //点击了弹出框中侧边栏的哪个栏目
  chooseCondition(e) {
    console.log(e)
    if (e.detail == 0) {
      this.setData({
        projectList: [],
        conditionWhere: ['扶助困难群体', '发展农业生产', '促进邻里互助', '倡导文明风尚', '关怀儿童教育', '协调冲突矛盾', '保护生态环境', '其它']
      })
      this.getProjectList()
    } else if (e.detail == 1) {
      this.setData({
        projectList: [],
        conditionWhere: ['扶助困难群体']
      })
      this.getProjectList()
    } else if (e.detail == 2) {
      this.setData({
        projectList: [],
        conditionWhere: ['发展农业生产']
      })
      this.getProjectList()
    } else if (e.detail == 3) {
      this.setData({
        projectList: [],
        conditionWhere: ['促进邻里互助']
      })
      this.getProjectList()
    } else if (e.detail == 4) {
      this.setData({
        projectList: [],
        conditionWhere: ['倡导文明风尚']
      })
      this.getProjectList()
    } else if (e.detail == 5) {
      this.setData({
        projectList: [],
        conditionWhere: ['关怀儿童教育']
      })
      this.getProjectList()
    } else if (e.detail == 6) {
      this.setData({
        projectList: [],
        conditionWhere: ['协调冲突矛盾']
      })
      this.getProjectList()
    } else if (e.detail == 7) {
      this.setData({
        projectList: [],
        conditionWhere: ['保护生态环境']
      })
      this.getProjectList()
    } else if (e.detail == 8) {
      this.setData({
        projectList: [],
        conditionWhere: ['其它']
      })
      this.getProjectList()
    }
  },
  //获取库里的项目数据，调用云函数（小石头的分页）
  getProjectList() {
    wx.showLoading({ //请求数据时的加载中弹窗
      title: '加载中',
    })
    wx.cloud.callFunction({
        name: "getProjectList",
        data: {
          len: this.data.projectList.length,
          pageNum: 10, //每页加载多少条数据,
          order: this.data.order,
          conditionWhere: this.data.conditionWhere,
          flag: "project"
        }
      }).then(res => {
        console.log("请求项目列表成功", res)
        //拖到没数据了
        // if (res.result.data <= 0) {
        //   wx.showToast({
        //     title: '没有更多数据啦',
        //     icon: "none"
        //   })
        // } else {
        wx.hideLoading()
        this.setData({
          projectList: this.data.projectList.concat(res.result.data) //concat方法就是把括号内的东西加到数组后
        })
        console.log(this.data.projectList.length)
        // }

      })
      .catch(err => {
        console.log("请求项目列表失败", err)
      })
  },
  //下拉到底部获取新的十条数据
  getMoreProjects(e) {
    console.log(e)
    // console.log("下拉了",this.data.initProjectHeight)
    // this.setData({
    //   initProjectHeight: this.data.projectHeight * this.data.projectList.length+this.data.nextBarHeight
    // })
    // console.log("下拉了",this.data.initProjectHeight)
    this.getProjectList()
  },
  //按发布时间降序升序
  timeOrder() {
    if (this.data.order == 'asc') {
      this.setData({
        projectList: [],
        order: 'desc'
      })
      console.log(this.data.order)
      this.getProjectList()
    } else if (this.data.order == 'desc') {
      this.setData({
        projectList: [],
        order: 'asc'
      })
      console.log(this.data.order)
      this.getProjectList()
    }
  },
  goProjectDetail(e) {
    console.log(e.currentTarget.dataset.id)
    wx.navigateTo({
      url: '/pages/project_all/projectDetail/projectDetail?id=' + e.currentTarget.dataset.id, //跟wxml里的data-id联动
    })
  },
  //*******************************************这是一条分割线**************************/

  //这是图文的方法
  getText() {
    return wx.cloud.callFunction({
      name:"getProjectList",
      data:{
        flag:"getTextAndPic"
      }
    }).then(res=>{
      console.log("获取图文成功",res)
        this.setData({
          textList: res.result.data 
        })
      console.log("图文列表",this.data.textList)
    }).catch(err=>{
      console.log("获取图文失败",err)
    })
    
    // db.collection('textAndPic')
    //   .get()
    //   .then(res => {
    //     console.log("请求图文列表成功", res.data)
    //     this.setData({
    //       textList: res.data
    //     })
    //   })
  },

  //点赞方法
  async zan(e) {
    var textID = e.currentTarget.dataset.id
    console.log(e)
    db.collection('textAndPic')
      .where({
        _id: e.currentTarget.dataset.id
      })
      .get()
      .then(res => {
        console.log("对应的图文", res)
        Zan = res.data[0].zan
        console.log(Zan)
        let cansole = Zan.findIndex(e => e._id == app.globalData.openid)
        console.log("findIndex", cansole)
        for (var i = 0; i < Zan.length; i++) {
          //现在是已经点赞的状态，点击应该是取消点赞，并且从Zan数组中扔出去
          //缓存中为true,现在应该改为flase
          if (Zan[i]._id == app.globalData.openid) {
            Zan.splice(cansole, 1)
            db.collection('textAndPic')
              .doc(e.currentTarget.dataset.id)
              .update({
                data: {
                  zan: Zan
                }
              })
              .then(res => {
                this.getText()
                likeCollection = wx.getStorageSync('likeCollection')
                //把缓存拿出来，找到对应文章的状态，本地改了之后存缓存
                console.log("likeCollection", likeCollection)
                let index1 = likeCollection.findIndex(e => ["e." + textID] != null)
                console.log("index1", index1)
                likeCollection[index1][textID] = false
                wx.setStorageSync('likeCollection', likeCollection)
                this.getZanStrogeTo()
                console.log("likeCollection", likeCollection)
                console.log("取消点赞成功", res)
              })
          }
          //用户没用点过赞--点击应该点zan
          //0-完全没有点过赞
          //1-点赞后又取消了，现在是未点赞状态
        }
        if (cansole == -1) {
          likeCollection = wx.getStorageSync('likeCollection')
          let index = likeCollection.findIndex(e => ["e." + textID] != null)
          console.log("index", index)
          //完全没有点过赞
          if (index == -1) {
            likeCollection.push({
              [textID]: true
            })
            wx.setStorageSync('likeCollection', likeCollection)
          }
          if (index != -1) {
            likeCollection = wx.getStorageSync('likeCollection')
            likeCollection[index][textID] = true
            wx.setStorageSync('likeCollection', likeCollection)
          }
          db.collection('textAndPic')
            .doc(e.currentTarget.dataset.id)
            .update({
              data: {
                zan: _.push({
                  _id: app.globalData.openid,
                  //name:app.globalData.userInfo.userInfo.name,
                  //avaUrl:app.globalData.userInfo.userInfo.avaUrl,
                })
              }
            })
            .then(async res => {
              await this.getText()
              this.getZanStrogeTo()
              console.log("点赞成功", res)
            })

        }
      })

  },
  // previewImage(event) {
  //   console.log(event.currentTarget.dataset.Url)
  //   let currentUrl = event.currentTarget.dataset.Url
  //   wx.previewImage({
  //     current: currentUrl, // 当前显示图片的http链接
  //     urls:currentUrl  // 需要预览的图片http链接列表
  //   })
  // },
  goTextDetail(e) {
    console.log("ben", e)
    console.log("文本ID", e.currentTarget.dataset.id)
    wx.navigateTo({
      url: '../project_all/texPicDetail/texPicDetail?id=' + e.currentTarget.dataset.id,
    })
  },
  //获取缓存中篾条动态的转态，并且加入到textList中
  getZanStrogeTo() {
    likeCollection = wx.getStorageSync('likeCollection')
    this.data.textList.forEach((item) => {
      for (var i = 0; i < likeCollection.length; i++) {
        if (likeCollection[i][item._id] != "") {
          item['hasChange'] = likeCollection[i][item._id]
        } else {
          item['hasChange'] = false
        }
      }
    });
    console.log("this.data.textList", this.data.textList)
    this.setData({
      textList: this.data.textList,
    })
  },

  //***************************这是一条分割线********************************

  //团队的方法
  //获取库里的《团队》数据，调用云函数（小石头的分页）
  getTeamList() {
    wx.showLoading({ //请求数据时的加载中弹窗
      title: '加载中',
    })
    wx.cloud.callFunction({
        name: "getProjectList",
        data: {
          len: this.data.teamList.length,
          pageNum: 10, //每页加载多少条数据,
          flag: "team",
        }
      }).then(res => {
        console.log("请求团队列表成功", res)
        //拖到没数据了
        // if (res.result.data <= 0) {
        //   wx.showToast({
        //     title: '没有更多数据啦',
        //     icon: "none"
        //   })
        // } else {
        wx.hideLoading()
        this.setData({
          teamList: this.data.teamList.concat(res.result.data) //concat方法就是把括号内的东西加到数组后
        })
        console.log("teamList的长度", this.data.teamList)
        // }

      })
      .catch(err => {
        console.log("请求项目列表失败", err)
      })
  },
  //下拉到底部获取新的十条数据
  getMoreTeam(e) {
    console.log(e)
    this.getTeamList()
  },
  goTeamDetail(e) {
    console.log(e.currentTarget.dataset.id)
    wx.navigateTo({
      url: "../../pages/project_all/teamDetail/teamDetail?id=" + e.currentTarget.dataset.id, //跟wxml里的data-id联动
    })
  },

  //////////////////////废弃的点赞功能********************勿删*****************************
//   zan1(e){
//     this.getZanStatus()
//     console.log("project的赞",e)
//    isZan=!isZan
//    setTimeout(()=> {
//    this.setData({
//     zanUrl:isZan?"../../images/zan.png":"../../images/no_zan.png"
//    })
//  },300)
//    this.updateZan()
//    var value=0;
//    if(isZan){
//      value=1;
//    }
//    else{
//      value=-1;
//    }
//    console.log(value)
//    wx.cloud.callFunction({
//      name:"collect",
//      data:{
//        action:"zan",
//        textID:textID,
//        value:value,
//      }
//    })
//    .then(res=>{
//      console.log("点赞+1")
//    })
//  },
//  getZanStatus1(){
//    let textStorge=wx.getStorageSync("text")
//    console.log("文本缓存",textStorge)
//    for(var i=0;i<textStorge.length;i++)
//    {
//        var temp
//        if(textStorge[i]._id==textID)
//        {
//            console.log(textStorge[i].user)
//            let user=textStorge[i].user
//            console.log("user01",user)
//            if(user=="")   
//            {
//             textStorge[i].user.push({
//                 _id:app.globalData.openid,
//                 zanStatus:false
//             })
//            }
//            else{
//                for(var j=0;j<user.length;j++)
//                {
//                   if(user=="")   
//                   {
//                    textStorge[i].user.push({
//                        _id:app.globalData.openid,
//                        zanStatus:false
//                    })
//                   }
//                   else if(user[j]._id==app.globalData.openid)
//                   {
//                       isZan=user[j].zanStatus
//                       temp=user[j].zanStatus
//                       if(temp!="")
//                       {
//                        this.setData({
//                            zanUrl:isZan?"../../images/zan.png":"../../images/no_zan.png"
//                           })
//                       }
//                       else
//                       {
//                        textStorge[i].user.push({
//                            _id:app.globalData.openid,
//                            zanStatus:false
//                        })
//                       }
//                   }
//                }
//            }
//        }
//    }
//    wx.setStorageSync('text', textStorge)
//  },
//  updateZan(e){
//    let textStorge=wx.getStorageSync("text")
//    console.log("文本缓存",textStorge)
//    for(var i=0;i<textStorge.length;i++)
//    {
//        if(textStorge[i]._id==e)
//        {
//            let user=textStorge[i].user
//            console.log("user1",user)
//                for(let j=0;j<user.length;j++)
//                {
//                    if(user[j]._id==app.globalData.openid)
//                   {
//                       textStorge[i].user[j].zanStatus=!textStorge[i].user[j].zanStatus
//                   }
//                }
//        }
//    }
//    console.log("更新点赞状态成功")
//    wx.setStorageSync('text', textStorge)
//  },
// collect() {
//   this.setData({
//     colUrl: isCollect ? "../../images/collect.png" : "../../images/no_coll.png"
//   })
//   wx.cloud.callFunction({
//       name: "collect",
//       data: {
//         textID: textID,
//         isCollect: isCollect,
//         action: "collect"
//       }
//     })
//     .then(res => {
//       console.log("改变收藏状态成功", res)
//     })
//     .catch(err => {
//       console.log("改变收藏状态成功", err)
//     })
//   isCollect = !isCollect
// },
/////////////**********************************************勿删************************* */
   getuserInfo()
   {
    db.collection('all_user')
    .where({
      _openid:app.globalData.openid
    })
    .get()
    .then(res=>{
       console.log("用户数据",res.data[0].userInfo)
       this.setData({
         userInfo:res.data[0].userInfo
       })

    })


   },

onLoad: async function(options) {
  this.getuserInfo()
  console.log('xxxxxxxx');
  wx.hideTabBar()
  await this.getText()
  likeCollection = wx.getStorageSync('likeCollection');
  if(!likeCollection){
    wx.setStorageSync('likeCollection', [])
  }
  app.editTabbar()
  this.getProjectList()
  this.getTeamList()
  //获取除底部和顶部导航栏外的可显示窗口高度
  console.log("可显示窗口宽度", wx.getSystemInfoSync().windowWidth)
    this.setData({
      windowHeight: wx.getSystemInfoSync().windowHeight - (wx.getSystemInfoSync().windowWidth) / 750 * 98
    })
  /*
  // const query = wx.createSelectorQuery()
  //     query.select('.nextTab').boundingClientRect()
  //     query.selectViewport().scrollOffset()
  //     query.exec(res => {
  //       console.log('"按发布时间那一个view的高度"', res[0].height);
  //       this.setData({
  //         nextBarHeight:res[0].height
  //       })
  //     })
  */
  this.getZanStrogeTo()
  let pp=String(new Date())
  console.log("!!11",pp)
  console.log("!!11",pp.slice(19,21))
},
 async onShow()
   {
    wx.hideTabBar()
    app.editTabbar()
    await this.getText()
    this.getZanStrogeTo()
  }
})